package com.pai4j.aigc.service;

import com.pai4j.aigc.llm.LlmSummarizerService;
import com.pai4j.common.bean.PAIResponseBean;
import com.pai4j.common.bean.PAIResponseBeanUtil;
import com.pai4j.common.enums.RoleCodeEnum;
import com.pai4j.common.util.JsonUtil;
import com.pai4j.domain.vo.response.UserBaseResponseInfoVO;
import com.pai4j.domain.vo.response.chatting.ChattingListResponseVO;
import com.pai4j.domain.vo.response.mess.ChatMessageResponseVO;
import com.pai4j.remote.ugc.ChatMessageClient;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Service
public class UnreadChatSummaryService {

    @Resource
    private ChatMessageClient chatMessageClient;

    @Resource
    private LlmSummarizerService summarizerService;

    public String summarizeUnread(String account, Integer maxConvs, Integer maxMsgsPerConv) {
        int convLimit = maxConvs == null || maxConvs <= 0 ? 5 : Math.min(maxConvs, 20);
        int msgLimit = maxMsgsPerConv == null || maxMsgsPerConv <= 0 ? 5 : Math.min(maxMsgsPerConv, 20);

        // 1) 拉取最近对话并筛选未读会话
        PAIResponseBean<List<ChattingListResponseVO>> chatListResp = chatMessageClient.listChatting(account, null, 200);
        if (!PAIResponseBeanUtil.isOk(chatListResp) || CollectionUtils.isEmpty(chatListResp.getData())) {
            log.info("未找到对话列表或接口失败，返回空摘要");
            return "暂无未读消息";
        }
        List<ChattingListResponseVO> unreadConvs = chatListResp.getData().stream()
                .filter(Objects::nonNull)
                .filter(ChattingListResponseVO::isUnread)
                .limit(convLimit)
                .collect(Collectors.toList());
        if (unreadConvs.isEmpty()) {
            return "暂无未读消息";
        }

        // 2) 为每个未读会话抓取最近若干条消息
        List<Map<String, Object>> convs = new ArrayList<>();
        for (ChattingListResponseVO conv : unreadConvs) {
            UserBaseResponseInfoVO user = conv.getUser();
            if (user == null || StringUtils.isBlank(user.getUserId())) {
                continue;
            }
            String partnerId = user.getUserId();
            boolean isGroup = RoleCodeEnum.GROUP.getCode().equals(user.getRoleCode());
            String name = StringUtils.isNotBlank(user.getUserName()) ? user.getUserName() : (StringUtils.isNotBlank(user.getPaiId()) ? user.getPaiId() : partnerId);

            PAIResponseBean<List<ChatMessageResponseVO>> listResp = chatMessageClient.list(account, partnerId, msgLimit, null, null);
            List<ChatMessageResponseVO> msgs = PAIResponseBeanUtil.isOk(listResp) && listResp.getData() != null ? listResp.getData() : Collections.emptyList();

            List<Map<String, Object>> samples = msgs.stream().limit(msgLimit).map(m -> {
                Map<String, Object> mm = new HashMap<>();
                mm.put("time", m.getTime());
                mm.put("type", m.getType());
                mm.put("isRead", m.getIsRead());
                mm.put("groupMessage", m.getGroupMessage());
                mm.put("senderId", m.getSender() != null ? m.getSender().getUserId() : m.getSenderId());
                mm.put("senderName", m.getSender() != null ? m.getSender().getUserName() : m.getSenderId());
                mm.put("message", safeText(m.getMessage()));
                return mm;
            }).collect(Collectors.toList());

            Map<String, Object> c = new HashMap<>();
            c.put("conversationId", partnerId);
            c.put("conversationName", name);
            c.put("isGroup", isGroup);
            c.put("unread", true);
            c.put("lastChatTime", conv.getLastChatTime());
            c.put("samples", samples);
            convs.add(c);
        }

        // 3) 构造模板变量并调用摘要
        Map<String, Object> vars = new HashMap<>();
        vars.put("account", account);
        vars.put("maxConvs", convLimit);
        vars.put("maxMsgsPerConv", msgLimit);
        vars.put("conversationsJson", JsonUtil.toJsonString(convs));

        return summarizerService.summarizeUnread(vars);
    }

    private String safeText(String s) {
        if (s == null) return "";
        String t = s.replaceAll("\\n", " ").trim();
        if (t.length() > 400) t = t.substring(0, 400);
        return t;
    }
}
